import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Button, Timeline, Spin, Row, Col } from 'antd';
import axios from 'axios';
import styles from './trailMap.less';
import carIcon from '@/assets/car.png';
import { getQueryString } from '@/utils/common';
import prompt from '@/components/Prompt';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { transferLanguage } from '@/utils/utils';

const topHeight = 69 + 24;
let marker;
let lineArr = [];
let infoWindow;
let carSpeed = 0;

const lineArr3 = [
  ['116.478935', '39.997761'],
  // ['116.478939', '39.997825'],
  // ['116.478912', '39.998549'],
  // ['116.478912', '39.998549'],
  // ['116.478998', '39.998555'],
  // ['116.478998', '39.998555'],
  // ['116.479282', '39.99856'],
  // ['116.479658', '39.998528'],
  // ['116.480151', '39.998453'],
  // ['116.480784', '39.998302'],
  // ['116.480784', '39.998302'],
  // ['116.481149', '39.998184'],
  // ['116.481573', '39.997997'],
  // ['116.481863', '39.997846'],
  // ['116.482072', '39.997718'],
  // ['116.482362', '39.997718'],
  // ['116.483633', '39.998935'],
  // ['116.48367', '39.998968'],
  ['116.484648', '39.999861'],
];
const cheInfo = {
  trackNo: 'OTC-2021203',
  cheLocation: '安徽省合肥市蜀山安徽永和厂,建和路130米',
  needKm: '200公里',
  needTime: '2小时',
  nowSpeed: '60km/h',
}
const statusList = [
  { title: 'Status', field: 'Arrived' },
  { title: 'Last node', field: 'Arrived' },
  { title: 'ETA', field: '2020-04-24 15:30:00' },
  { title: 'Planned Arrived Time', field: '2020-04-24 17:00:00' },
];
@connect(({ TraiMap, loading, i18n }) => ({
  loading: loading.effects['TraiMap/selectMapTracks'],
}))
export default class TrailMapUrl extends Component {
  state = {
    orderNo: '',
    hichainNo: '',
    timeLineList: [],
    lineArr: [],
    isHiddenTopLeft: 0,
    trackList: [],
    endLine:[],
    startLine:[],
  };

  componentDidMount() {
    const {match: { path }, location: { query: { token, customerCode, orderNo, type, isHiddenTopLeft } }, location } = this.props
    this.setState({ isHiddenTopLeft, orderNo })
    const _params={
      orderNo,
      type:type,
    }
    if (path && path.indexOf('trailMap') != -1) {
      _params.customerCode=''
      _params.type='HIC'
    }else{
      _params.customerCode=customerCode
      _params.token=token
    }
    this.getMapTracks(_params);
  }
  //去重方法
  removelal=(arr)=>{

    let newArr=[]
    for(let i=0;i<arr.length;i++){
      if(newArr.length>0){
        if(newArr.findIndex(item=>item.status===arr[i].status)===-1){
          newArr.push(arr[i])
          // newArr=[...newArr,arr[i]]
          console.log('?????',arr[i],newArr)
        }
      }else{
        newArr.push(arr[i])
      }
    }
    // arr.forEach((v,index)=>{
    //   if(newArr.length>0){
    //     if(newArr.findIndex(item=>item.status===v.status)===-1){
    //       newArr.push(v)
    //       console.log('?????',v,newArr.length)
    //       return
    //     }
    //   }else{
    //     newArr.push(v)
    //   }
    // })
    return newArr
    // return [...new Set(arr)]
  }
  getMapTracks = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'TraiMap/selectMapTracks',
      payload: params,
      callback: res => {
        this.setState({ hichainNo: res.orderNo })
        const timeArr = res.trackingList.map(v => {
          return { time: v.eventTime, status: v.eventDesc }
        })

        // 信息数据去重
        let testArr=[{status:1},{status:1},{status:3},{status:4},{status:5},{status:5},{status:5}]

        const newTimeArr=this.removelal(timeArr.reverse())
        // const newTimeArr=this.removelal(testArr)
        // console.log('newTimeArr===',newTimeArr)
        const startLine = ([res.fromLongitude, res.fromLatitude]);
        const codeLine = res.trackingList.filter(v => v.positionLongitude).map(o => {
          return [o.positionLongitude, o.positionLatitude]
        })
        const endLine = ([res.toLongitude, res.toLatitude])
        // let _arr = codeLine.length > 0 ? ([startLine, ...codeLine, endLine]) : ([startLine, endLine])
        let _arr = codeLine.length > 0 ? codeLine: ([startLine, endLine])
        const contentArr = res.trackingList.filter(v => {
          return v.positionLongitude
        })
        const unPolylineList=res.planPolylineList
        this.setState({
          timeLineList: newTimeArr.slice(0,10),
          lineArr: _arr,
          endLine,
          startLine,
          // trackList:res.trackingList
        })

        this.setMap(_arr, contentArr,unPolylineList);
      },
    });
  };
  //计算经纬度距离和耗时 lat:纬度  lng：经度
  getKMTime = (lng1, lat1, lng2, lat2, ) => {
    if ((Math.abs(lat1) > 90) || (Math.abs(lat2) > 90)) {
      prompt({ content: '纬度错误', type: 'warn' })
      return
    }
    if ((Math.abs(lng1) > 180) || (Math.abs(lng2) > 180)) {
      prompt({ content: '经度错误', type: 'warn' })
      return
    }
    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    return
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + (Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))));

    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    console.log('s', s)
    return s;

  }
  setMap = (lineArr, dataList,unLineArr) => {
    const { orderNo,endLine,startLine } = this.state
    const cheInfo = dataList.length > 0 ? dataList[0] : {}
    let { remainingMileage = 0, currentSpeed = 0, position = '', sourceCode = '' } = cheInfo
    //测试

    //创建地图
    var map = new AMap.Map('container', {
      resizeEnable: true,
      //   center: [116.397428, 39.90923],
      center: lineArr[0],
      layers: [
        // 卫星
        new AMap.TileLayer.Satellite(),
        // 路网
        new AMap.TileLayer.RoadNet(),
      ],
      zoom: 17,
    });
    //给地图添加标记 ：map.add(marker) 移除：map.remove(marker)
    marker = new AMap.Marker({
      map: map,
      position: lineArr[0], //[116.478935, 39.997761]
      icon: carIcon,
      offset: new AMap.Pixel(-26, -19),
      autoRotation: true,
      angle: -90,
    });

    // 创建一个 Icon
    var startIcon = new AMap.Icon({
      // 图标尺寸
      size: new AMap.Size(25, 34),
      // 图标的取图地址
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
      // 图标所用图片大小
      imageSize: new AMap.Size(135, 40),
      // 图标取图偏移量
      imageOffset: new AMap.Pixel(-9, -3),
    });
    // 将 icon 传入 marker
    var startMarker = new AMap.Marker({
      position: startLine,
      icon: startIcon,
      offset: new AMap.Pixel(-13, -30)
    });
    // 创建一个 icon
    var endIcon = new AMap.Icon({
      size: new AMap.Size(25, 34),
      image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
      imageSize: new AMap.Size(135, 40),
      imageOffset: new AMap.Pixel(-95, -3)
    });
    // 将 icon 传入 marker
    var endMarker = new AMap.Marker({
      position: endLine,
      icon: endIcon,
      offset: new AMap.Pixel(-13, -30)
    });
    // 构造官方卫星、路网图层
    // var satelliteLayer = new AMap.TileLayer.Satellite();

    //批量添加图层
    // map.add([satelliteLayer]);
    //绘制 剩余路段
    var unPassedPolyline = new AMap.Polyline({
      map: map,
      path: unLineArr, //路线未经过的点
      showDir: true,
      strokeColor: '#28F', //线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, //线宽
      // strokeStyle: "solid"  //线样式
    });
    // 绘制轨迹
    var polyline = new AMap.Polyline({
      map: map,
      path: lineArr, //路线经过的点
      showDir: true,
      strokeColor: '#28F', //线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, //线宽
      // strokeStyle: "solid"  //线样式
    });

    var passedPolyline = new AMap.Polyline({
      map: map,
      // path: lineArr,
      strokeColor: '#AF5', //线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6, //线宽
      // strokeStyle: "solid"  //线样式
    });
    var infoWindow = new AMap.InfoWindow({
      // opacity:0.5,
      isCustom: true, // true 表示完全自定义窗体,
      autoMove: false,
      content: "<div style='background-color:rgba(255,255,255,0.6);color:#000;width:250px;' >"
        + "运单号：" + orderNo + "<br>" +
        "当前位置：" + (position || '') + "<br>" +
        "剩余里程：" + (remainingMileage || 0) + "<br>" +
        "预计剩余时间：" + (cheInfo.remainingHour || '0小时') + "<br>" +
        "当前车速：" + (currentSpeed || 0)
        + "</div>",

    })
    map.add([startMarker, endMarker]);

    marker.on('moving', function (e) {
      passedPolyline.setPath(e.passedPath);
    });
    AMap.event.addListener(marker, 'moving', function (e) {
      var lastLocation = e.passedPath[e.passedPath.length - 1];
      infoWindow.setPosition(lastLocation);
      setVehicleSpeedInWidowns(lastLocation);
    });
    infoWindow.open(map, marker.getPosition())
    map.setFitView();
    this.startAnimation();
    function setVehicleSpeedInWidowns(lnglat) {
      for (let i = 0; i < dataList.length; i++) {
        if (lnglat.lat == dataList[i].positionLatitude && lnglat.lng == dataList[i].positionLongitude) {
          infoWindow.setContent(
            "<div style='background-color:rgba(255,255,255,0.6);color:#000;width:250px;' >"
            + "运单号：" + orderNo + "<br>" +
            "当前位置：" + (dataList[i].position || '') + "<br>" +
            "剩余里程：" + (dataList[i].remainingMileage || 0) + "<br>" +
            "预计剩余时间：" + (dataList[i].remainingHour || '0小时') + "<br>" +
            "当前车速：" + (dataList[i].currentSpeed || 0)
            + "</div>",

          );
          return;
        }
      }
    }
  };

  startAnimation = () => {
    const { lineArr } = this.state
    marker.moveAlong(lineArr, 100000);
  };

  pauseAnimation() {
    marker.pauseMove();
  }

  resumeAnimation() {
    marker.resumeMove();
  }

  stopAnimation() {
    marker.stopMove();
  }

  render() {
    const { loading } = this.props;
    const { timeLineList, orderNo, hichainNo, isHiddenTopLeft } = this.state
    const showTopLeft = parseInt(isHiddenTopLeft)
    return (
      <GridContent id="containerBox" style={{ width: '100%', height: 'calc(100vh - 65px)' }}>
        <Row gutter={24}>
          <Col lg={!showTopLeft ? 19 : 24} md={24}>
            <Fragment>
              {!showTopLeft && <div>
                <div className={styles.c_title}>
                  {'Real-time tracking of orders -' + hichainNo + ' - queryNo - ' + orderNo}
                </div>
                <div className={styles.desBox}>
                  {statusList.map(v => {
                    return (
                      <div className={styles.des_item}>
                        <div className={styles.des_title}>{v.title}</div>
                        <div className={styles.des_con}>{v.field}</div>
                      </div>
                    );
                  })}
                </div>
              </div>
              }
              <Spin spinning={loading}>
                <div id="container" style={{ width: '100%', height: showTopLeft ? 'calc(100vh - 4px)' : 'calc(100vh - 125px)' }}></div>
              </Spin>
              {/* {!showTopLeft &&
                <div className="input-card">
                  <h4>Playback control</h4>
                  <div className="input-item">
                    <input
                      type="button"
                      className="btn"
                      value="Start"
                      id="start"
                      onClick={this.startAnimation}
                    />
                    <input
                      type="button"
                      className="btn"
                      value="Pause"
                      id="pause"
                      onClick={() => this.pauseAnimation()}
                    />
                  </div>
                </div>
              } */}
            </Fragment>
          </Col>
          {!showTopLeft && <Col lg={5} md={24}>
            <div className={styles.rightBox} >
              <div className={styles.c_title}>Nodal time axis</div>
              <div style={{ padding: 15 }}>
                <Timeline>
                  {timeLineList.map((v, index) => {
                    return (
                      <Timeline.Item>
                        <div className={styles.timelineBox} style={{ color: index == 0 ? 'red' : '', }}>
                          <span className={styles.trail_time}>{v.time}</span>
                          <span className={styles.trail_des}>{v.status}</span>
                        </div>
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
              </div>
            </div>

          </Col>}
        </Row>

      </GridContent>
      
    );
  }
}
